<template>
  <van-button
    v-if="value"
    class="follow-btn"
    round
    size="small"
    :loading="followLoading"
    @click="onFollow"
    >已关注</van-button
  >
  <van-button
    v-else
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    @click="onFollow"
    icon="plus"
    :loading="followLoading"
    >关注</van-button
  >
</template>

<script>
import { addFollow, deleteFollow } from '@/api/user'
export default {
  name: 'FollowUser',
  props: {
    value: {
      type: Boolean,
      required: true
    },
    userId: {
      type: [Number, String, Object],
      required: true
    }
  },
  data () {
    return {
      followLoading: false
    }
  },
  methods: {
    async onFollow () {
      if (!this.$store.state.user.token) return this.$toast('请先登录')
      // 关闭加载状态
      this.followLoading = true
      try {
        if (this.value) {
          const res = await deleteFollow(this.userId)
          console.log(res, '删除关注')
        } else {
          const res = await addFollow(this.userId)
          console.log(res, '添加关注')
        }
        // 更新视图状态
        this.$emit('input', !this.value)
      } catch (error) {
        console.log(error)
        if (error && error.response.status === 400) {
          this.$toast('你不能关注自己')
        }
      }
      // 关闭按钮的 loading 状态
      this.followLoading = false
    }
  }
}
</script>

<style></style>
